package cn.com.yusys.yusp.admin.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Order(2)
@WebFilter(filterName = "LoginFilter",urlPatterns = "/ssomslogin.do")
public class LoginFilter implements Filter {

    @Value("${sso.ssoUrl}")
    private String ssoUrl;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
            throws IOException, ServletException{
        System.out.println("begin: ");
        HttpServletRequest request = (HttpServletRequest)arg0;
        HttpServletResponse response = (HttpServletResponse)arg1;
        HttpSession session=request.getSession();
        if(session.getAttribute("loginName")==null)
            System.out.println("loginName:null ");
        String userId=(String) session.getAttribute("loginName");
        System.out.println("userId: "+userId);
//    if (userId==null||userId.equals(""))
//    	userId="admin";
        if(userId !=null && !userId.equals("")){
            session.setAttribute("userId", userId);
            String url = request.getRequestURI();
            System.out.println("url :"+url);
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.sendRedirect(ssoUrl+"?SSO_USER_TOKEN=true");
        }else{
            response.sendRedirect(ssoUrl); // 失败去登录页面
        }
    }

    @Override
    public void destroy() {

    }
}
